<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['writer:writer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['writer:writer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['writer:writer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['writer:writer:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="writerList" @selection-change="handleSelectionChange" class="novel-table">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="封面" align="center" width="120">
        <template slot-scope="scope">
          <el-image 
            :src="scope.row.coverUrl" 
            :preview-src-list="[scope.row.coverUrl]"
            class="novel-cover"
            fit="cover">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="小说名称" align="center" prop="title" min-width="180">
        <template slot-scope="scope">
          <span class="novel-title">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作者" align="center" prop="authorName" min-width="120" />
      <el-table-column label="分类" align="center" prop="categoryName" min-width="120" />
      <el-table-column label="阅读量" align="center" prop="pass" min-width="120">
        <template slot-scope="scope">
          <span class="stat-value">{{ formatNumber(scope.row.pass) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="打赏" align="center" prop="tipping" min-width="120">
        <template slot-scope="scope">
          <span class="stat-value">¥{{ formatNumber(scope.row.tipping) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="点击量" align="center" prop="clicks" min-width="120">
        <template slot-scope="scope">
          <span class="stat-value">{{ formatNumber(scope.row.clicks) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收藏数" align="center" prop="collection" min-width="120">
        <template slot-scope="scope">
          <span class="stat-value">{{ formatNumber(scope.row.collection) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['writer:writer:edit']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改写作对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="小说名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入小说名称" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryName">
          <el-select v-model="form.categoryName" placeholder="请选择分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">更新中</el-radio>
            <el-radio label="1">已完结</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input type="textarea" v-model="form.description" placeholder="请输入小说简介" />
        </el-form-item>
        <el-form-item label="封面" prop="coverUrl">
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="handleUpload"
            :show-file-list="false">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
          <el-image 
            v-if="form.coverUrl"
            :src="form.coverUrl" 
            class="preview-image"
            fit="cover">
          </el-image>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWriter, getWriter, delWriter, addNovel, updateWriter, getUserNovel, uploadCover } from "@/api/writer/writer";
import store from "@/store";
export default {
  name: "Writer",
  data() {
    return {
      userId: store.state.user.id,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 写作表格数据
      writerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      categoryOptions: [
        '玄幻', '都市', '仙侠', '科幻', '历史', '游戏', '悬疑', '奇幻',
        '武侠', '军事', '古代言情', '现代言情', '仙侠奇缘', '玄幻言情',
        '浪漫青春', '快穿', '穿书', '重生', '甜宠', '豪门'
      ],
      // 表单参数
      form: {
        title: '',
        authorId: store.state.user.id,
        author_name: '',
        categoryId: '',
        categoryName: '',
        status: '0',
        description: '',
        coverUrl: '',
        createTime: ''
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: "小说名称不能为空", trigger: "blur" }
        ],
        categoryName: [
          { required: true, message: "请选择分类", trigger: "change" }
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "change" }
        ],
        description: [
          { required: true, message: "简介不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询写作列表 */
    getList() {
      this.loading = true;
      getUserNovel(this.userId).then(response => {
        console.log('API响应数据:', response);
        if (response && response.data) {
          const allData = Array.isArray(response.data) ? response.data : [response.data];
          console.log('处理后的数据:', allData);
          // 计算总条数
          this.total = allData.length;
          // 计算当前页的数据
          const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
          const end = start + this.queryParams.pageSize;
          this.writerList = allData.slice(start, end);
          console.log('当前页数据:', this.writerList);
        } else {
          this.writerList = [];
          this.total = 0;
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取数据失败:', error);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        title: '',
        authorId: this.userId,
        author_name: '',
        categoryId: '',
        categoryName: '',
        status: '0',
        description: '',
        coverUrl: '',
        createTime: ''
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增小说";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWriter(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改写作";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 设置创建时间
          const now = new Date();
          this.form.createTime = now.getFullYear() + '-' +
            String(now.getMonth() + 1).padStart(2, '0') + '-' +
            String(now.getDate()).padStart(2, '0') + ' ' +
            String(now.getHours()).padStart(2, '0') + ':' +
            String(now.getMinutes()).padStart(2, '0') + ':' +
            String(now.getSeconds()).padStart(2, '0');
          
          addNovel(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除写作编号为"' + ids + '"的数据项？').then(function() {
        return delWriter(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('writer/writer/export', {
        ...this.queryParams
      }, `writer_${new Date().getTime()}.xlsx`)
    },
    // 格式化数字（添加千分位）
    formatNumber(num) {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.$router.push({
        path: '/writer/novelDetail',
        query: {
          title: row.title
        }
      });
    },
    // 处理文件上传
    handleUpload(file) {
      const formData = new FormData();
      formData.append('file', file.file);
      uploadCover(formData).then(response => {
        if (response.code === 200) {
          this.form.coverUrl = response.data.url; // 只保存url
          this.$message.success('上传成功');
        } else {
          this.$message.error('上传失败');
        }
      });
    },
  }
};
</script>

<style scoped>
.novel-table {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  font-size: 14px;
  width: 100%;
}

.novel-cover {
  width: 80px;
  height: 110px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  transition: transform 0.3s;
}

.novel-cover:hover {
  transform: scale(1.05);
}

.novel-title {
  font-weight: bold;
  color: #303133;
  font-size: 16px;
}

.stat-value {
  font-weight: bold;
  color: #409EFF;
  font-size: 16px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.el-table {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: bold;
  font-size: 16px;
  padding: 12px 0;
}

.el-button--text {
  padding: 8px 15px;
  font-size: 15px;
}

.el-button--text:hover {
  background-color: #ecf5ff;
  border-radius: 4px;
}

.app-container {
  padding: 20px;
}
</style>
